package com.changyou.kf.mock.service;

import com.changyou.kf.mock.entity.RoleInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class GameLoginService {

    private Logger GAME_LOG_CHAT = LoggerFactory.getLogger("GAME_LOG_CHAT");

    private String CHAT_FORMAT = "%s\u0001%s\u00011.11.21\u0001chat\u00011.0.0\u0001C2020\u0001%s\u00012019112001\u00011716094984440493\u0001%s\u000165\u00010\u0001E2:7C:98:A5:29:A8\u0001%s\u0001text\u0001%s\u0001%s\u00011\u0001%s\u00010d70cb6f8eb0\u00010\u0001%s\u000110.12.0.38";

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final Map<String, RoleInfo> appkeyRoleInfoMap = new ConcurrentHashMap<>();

    private String appkey = "1643093398001";

    private String channelId = "99";

    public void addRoleInfo(RoleInfo roleInfo) {
        String roleId = roleInfo.getRoleId();
        if (StringUtils.isEmpty(roleId)) {
            return;
        }
        roleInfo.setAppkey(appkey);
        roleInfo.setChannelId(channelId);
        if (StringUtils.isEmpty(roleInfo.getRoleName())) {
            roleInfo.setRoleName("角色名(roleId)");
        }
        appkeyRoleInfoMap.put(roleInfo.getRoleId(), roleInfo);
    }

    public void removeRoleInfo(String roleId) {
        if (StringUtils.isEmpty(roleId)) {
            return;
        }
        log.info("removeRoleInfo roleId:{}", roleId);
        appkeyRoleInfoMap.remove(roleId);
    }

    public RoleInfo getRoleInfo(String roleId) {
        RoleInfo roleInfo = appkeyRoleInfoMap.get(roleId);
        return roleInfo;
    }

    public Map<String, RoleInfo> getRoleInfoMap() {
        return appkeyRoleInfoMap;
    }

    public void writeChatMessage(String appkey, String serverId, String roleId,
                                         String roleName, String message, String targetType, String targetId) {
        LocalDateTime dateTime = LocalDateTime.now();
        String date = dateTime.format(dateTimeFormatter);
        String chatMsg = String.format(CHAT_FORMAT, date, appkey, serverId, roleId, targetType,
                message, targetId, roleName, message);
        log.info("writeChatMessage chatMsg:{}", chatMsg);
        GAME_LOG_CHAT.info(chatMsg);
    }

    public void writeChatMessage(RoleInfo roleInfo, String message) {
        writeChatMessage(roleInfo.getAppkey(), roleInfo.getServerId(),
                roleInfo.getRoleId(), roleInfo.getRoleName(), message,
                roleInfo.getChannelId(), roleInfo.getTargetRoleId());
    }
}
